package com.open.capacity.user.controller;

import com.open.capacity.annotation.log.LogAnnotation;
import com.open.capacity.commons.Result;
import com.open.capacity.model.system.SysUser;
import com.open.capacity.user.model.SysUserRelation;
import com.open.capacity.user.service.SysUserRelationService;
import com.open.capacity.user.service.SysUserService;
import com.open.capacity.vo.SysUserRelationExtVo;
import com.open.capacity.user.vo.SysUserRelationVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author 作者 ftquan E-mail: 464725602@qq.com
 * @version 创建时间：2017年11月12日 上午22:57:51
 * 用户关联
 */
@RestController
@Api(tags = "用户关联模块api")
public class SysUserRelationController {

    private static Logger logger = LoggerFactory.getLogger(SysUserRelationController.class);


    @Autowired
    private SysUserRelationService userRelationService;


    @Autowired
    private SysUserService userService;



    @PreAuthorize("hasAuthority('userRelation:get/userRelations/{objectId}')")
    @GetMapping("/userRelations/{objectId}")
    public Result<SysUserRelationExtVo> findUserRelationsByObjectId(@PathVariable(value = "objectId") String objectId) {
        SysUserRelationExtVo vo = new SysUserRelationExtVo();
        List<SysUserRelation> list = userRelationService.findByObjectId(objectId);
        String userIds = "";
        Set<SysUser> userSet=new HashSet<>();
        for (SysUserRelation item : list) {
            if (userIds != "") {
                userIds += ",";
            }
            userIds += item.getUserId();
            userSet.add(userService.findById(item.getUserId()));
        }
        vo.setUserInfoList(userSet);
        vo.setUserIds(userIds);
        return Result.succeed(vo);
    }


    /**
     * 用户关联新增或者更新
     *
     * @param sysUserRelation
     * @return
     */
    @PreAuthorize("hasAnyAuthority('userRelation:post/userRelations','userRelation:put/userRelations')")
    @ApiOperation(value = "保存用户关联")
    @PostMapping("/userRelations/saveOrUpdate")
    @LogAnnotation(module = "用户权限", name = "更新")
    public Result saveOrUpdate(@RequestBody SysUserRelationVo sysUserRelation) {
        return userRelationService.saveOrUpdate(sysUserRelation);
    }

}
